home *** CD-ROM | disk | FTP | other *** search
/ Aminet 1 (Walnut Creek) / Aminet - June 1993 [Walnut Creek].iso / aminet / util / gnu / textutl3.lha / textutils-1.3 / src / sort.c < prev    next >
C/C++ Source or Header  |  1992-06-29  |  39KB  |  1,741 lines

  1. /* sort - sort lines of text (with all kinds of options).
  2.    Copyright (C) 1988, 1991 Free Software Foundation
  3.  
  4.    This program is free software; you can redistribute it and/or modify
  5.    it under the terms of the GNU General Public License as published by
  6.    the Free Software Foundation; either version 2, or (at your option)
  7.    any later version.
  8.  
  9.    This program is distributed in the hope that it will be useful,
  10.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  11.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12.    GNU General Public License for more details.
  13.  
  14.    You should have received a copy of the GNU General Public License
  15.    along with this program; if not, write to the Free Software
  16.    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  17.  
  18.    Written December 1988 by Mike Haertel.
  19.    The author may be reached (Email) at the address mike@ai.mit.edu,
  20.    or (US mail) as Mike Haertel c/o Free Software Foundation. */
  21.  
  22. #define _GNU_SOURCE
  23. #include <ctype.h>
  24. #ifndef isblank
  25. #define isblank(c) ((c) == ' ' || (c) == '\t')
  26. #endif
  27. #include <sys/types.h>
  28. #include <signal.h>
  29. #include <stdio.h>
  30. #include "system.h"
  31. #ifdef _POSIX_VERSION
  32. #include <limits.h>
  33. #else
  34. #ifndef UCHAR_MAX
  35. #define UCHAR_MAX 255
  36. #endif
  37. #endif
  38. #ifndef STDC_HEADERS
  39. char *malloc ();
  40. char *realloc ();
  41. void free ();
  42. #endif
  43.  
  44. void error ();
  45. static void usage ();
  46.  
  47. #define min(a, b) ((a) < (b) ? (a) : (b))
  48. #define UCHAR_LIM (UCHAR_MAX + 1)
  49. #define UCHAR(c) ((unsigned char) (c))
  50.  
  51. #ifdef isascii
  52. #define ISALNUM(c) (isascii(c) && isalnum(c))
  53. #define ISDIGIT(c) (isascii(c) && isdigit(c))
  54. #define ISPRINT(c) (isascii(c) && isprint(c))
  55. #define ISLOWER(c) (isascii(c) && islower(c))
  56. #else
  57. #define ISALNUM(c) isalnum(c)
  58. #define ISDIGIT(c) isdigit(c)
  59. #define ISPRINT(c) isprint(c)
  60. #define ISLOWER(c) islower(c)
  61. #endif
  62.  
  63. /* The kind of blanks for '-b' to skip in various options. */
  64. enum blanktype { bl_start, bl_end, bl_both };
  65.  
  66. /* The name this program was run with. */
  67. char *program_name;
  68.  
  69. /* Table of digits. */
  70. static int digits[UCHAR_LIM];
  71.  
  72. /* Table of white space. */
  73. static int blanks[UCHAR_LIM];
  74.  
  75. /* Table of non-printing characters. */
  76. static int nonprinting[UCHAR_LIM];
  77.  
  78. /* Table of non-dictionary characters (not letters, digits, or blanks). */
  79. static int nondictionary[UCHAR_LIM];
  80.  
  81. /* Translation table folding lower case to upper. */
  82. static char fold_toupper[UCHAR_LIM];
  83.  
  84. /* Table mapping 3-letter month names to integers.
  85.    Alphabetic order allows binary search. */
  86. static struct month
  87. {
  88.   char *name;
  89.   int val;
  90. } monthtab[] =
  91. {
  92.   "APR", 4,
  93.   "AUG", 8,
  94.   "DEC", 12,
  95.   "FEB", 2,
  96.   "JAN", 1,
  97.   "JUL", 7,
  98.   "JUN", 6,
  99.   "MAR", 3,
  100.   "MAY", 5,
  101.   "NOV", 11,
  102.   "OCT", 10,
  103.   "SEP", 9
  104. };
  105.  
  106. /* During the merge phase, the number of files to merge at once. */
  107. #define NMERGE 16
  108.  
  109. /* Initial buffer size for in core sorting.  Will not grow unless a
  110.    line longer than this is seen. */
  111. static int sortalloc =  524288;
  112.  
  113. /* Initial buffer size for in core merge buffers.  Bear in mind that
  114.    up to NMERGE * mergealloc bytes may be allocated for merge buffers. */
  115. static int mergealloc =  16384;
  116.  
  117. /* Guess of average line length. */
  118. static int linelength = 30;
  119.  
  120. /* Maximum number of elements for the array(s) of struct line's, in bytes.  */
  121. #define LINEALLOC 262144
  122.  
  123. /* Prefix for temporary file names. */
  124. static char *prefix;
  125.  
  126. /* Flag to reverse the order of all comparisons. */
  127. static int reverse;
  128.  
  129. /* Flag for stable sort.  This turns off the last ditch bytewise
  130.    comparison of lines, and instead leaves lines in the same order
  131.    they were read if all keys compare equal.  */
  132. static int stable;
  133.  
  134. /* Tab character separating fields.  If NUL, then fields are separated
  135.    by the empty string between a non-whitespace character and a whitespace
  136.    character. */
  137. static char tab;
  138.  
  139. /* Flag to remove consecutive duplicate lines from the output.
  140.    Only the last of a sequence of equal lines will be output. */
  141. static int unique;
  142.  
  143. /* Nonzero if any of the input files are the standard input. */
  144. static int have_read_stdin;
  145.  
  146. /* Lines are held in core as counted strings. */
  147. struct line
  148. {
  149.   char *text;            /* Text of the line. */
  150.   int length;            /* Length not including final newline. */
  151.   char *keybeg;            /* Start of first key. */
  152.   char *keylim;            /* Limit of first key. */
  153. };
  154.  
  155. /* Arrays of lines. */
  156. struct lines
  157. {
  158.   struct line *lines;        /* Dynamically allocated array of lines. */
  159.   int used;            /* Number of slots used. */
  160.   int alloc;            /* Number of slots allocated. */
  161.   int limit;            /* Max number of slots to allocate.  */
  162. };
  163.  
  164. /* Input buffers. */
  165. struct buffer
  166. {
  167.   char *buf;            /* Dynamically allocated buffer. */
  168.   int used;            /* Number of bytes used. */
  169.   int alloc;            /* Number of bytes allocated. */
  170.   int left;            /* Number of bytes left after line parsing. */
  171. };
  172.  
  173. /* Lists of key field comparisons to be tried. */
  174. static struct keyfield
  175. {
  176.   int sword;            /* Zero-origin 'word' to start at. */
  177.   int schar;            /* Additional characters to skip. */
  178.   int skipsblanks;        /* Skip leading white space at start. */
  179.   int eword;            /* Zero-origin first word after field. */
  180.   int echar;            /* Additional characters in field. */
  181.   int skipeblanks;        /* Skip trailing white space at finish. */
  182.   int *ignore;            /* Boolean array of characters to ignore. */
  183.   char *translate;        /* Translation applied to characters. */
  184.   int numeric;            /* Flag for numeric comparison. */
  185.   int month;            /* Flag for comparison by month name. */
  186.   int reverse;            /* Reverse the sense of comparison. */
  187.   struct keyfield *next;    /* Next keyfield to try. */
  188. } keyhead;
  189.  
  190. /* The list of temporary files. */
  191. static struct tempnode
  192. {
  193.   char *name;
  194.   struct tempnode *next;
  195. } temphead;
  196.  
  197. /* Clean up any remaining temporary files. */
  198.  
  199. static void
  200. cleanup ()
  201. {
  202.   struct tempnode *node;
  203.  
  204.   for (node = temphead.next; node; node = node->next)
  205.     unlink (node->name);
  206. }
  207.  
  208. /* Allocate N bytes of memory dynamically, with error checking.  */
  209.  
  210. char *
  211. xmalloc (n)
  212.      unsigned n;
  213. {
  214.   char *p;
  215.  
  216.   p = malloc (n);
  217.   if (p == 0)
  218.     {
  219.       error (0, 0, "virtual memory exhausted");
  220.       cleanup ();
  221.       exit (2);
  222.     }
  223.   return p;
  224. }
  225.  
  226. /* Change the size of an allocated block of memory P to N bytes,
  227.    with error checking.
  228.    If P is NULL, run xmalloc.
  229.    If N is 0, run free and return NULL.  */
  230.  
  231. char *
  232. xrealloc (p, n)
  233.      char *p;
  234.      unsigned n;
  235. {
  236.   if (p == 0)
  237.     return xmalloc (n);
  238.   if (n == 0)
  239.     {
  240.       free (p);
  241.       return 0;
  242.     }
  243.   p = realloc (p, n);
  244.   if (p == 0)
  245.     {
  246.       error (0, 0, "virtual memory exhausted");
  247.       cleanup ();
  248.       exit (2);
  249.     }
  250.   return p;
  251. }
  252.  
  253. static FILE *
  254. xfopen (file, how)
  255.      char *file, *how;
  256. {
  257.   FILE *fp = strcmp (file, "-") ? fopen (file, how) : stdin;
  258.  
  259.   if (fp == 0)
  260.     {
  261.       error (0, errno, "%s", file);
  262.       cleanup ();
  263.       exit (2);
  264.     }
  265.   if (fp == stdin)
  266.     have_read_stdin = 1;
  267.   return fp;
  268. }
  269.  
  270. static void
  271. xfclose (fp)
  272.      FILE *fp;
  273. {
  274.   fflush (fp);
  275.   if (fp != stdin && fp != stdout)
  276.     {
  277.       if (fclose (fp) != 0)
  278.     {
  279.       error (0, errno, "error closing file");
  280.       cleanup ();
  281.       exit (2);
  282.     }
  283.     }
  284.   else
  285.     /* Allow reading stdin from tty more than once. */
  286.     clearerr (fp);
  287. }
  288.  
  289. static void
  290. xfwrite (buf, size, nelem, fp)
  291.      char *buf;
  292.      int size, nelem;
  293.      FILE *fp;
  294. {
  295.   if (fwrite (buf, size, nelem, fp) != nelem)
  296.     {
  297.       error (0, errno, "write error");
  298.       cleanup ();
  299.       exit (2);
  300.     }
  301. }
  302.  
  303. /* Return a name for a temporary file. */
  304.  
  305. static char *
  306. tempname ()
  307. {
  308.   static int seq;
  309.   int len = strlen (prefix);
  310.   char *name = xmalloc (len + 16);
  311.   struct tempnode *node =
  312.   (struct tempnode *) xmalloc (sizeof (struct tempnode));
  313.  
  314.   if (len && prefix[len - 1] != '/')
  315.     sprintf (name, "%s/sort%5.5d%5.5d", prefix, getpid (), ++seq);
  316.   else
  317.     sprintf (name, "%ssort%5.5d%5.5d", prefix, getpid (), ++seq);
  318.   node->name = name;
  319.   node->next = temphead.next;
  320.   temphead.next = node;
  321.   return name;
  322. }
  323.  
  324. /* Search through the list of temporary files for NAME;
  325.    remove it if it is found on the list. */
  326.  
  327. static void
  328. zaptemp (name)
  329.      char *name;
  330. {
  331.   struct tempnode *node, *temp;
  332.  
  333.   for (node = &temphead; node->next; node = node->next)
  334.     if (!strcmp (name, node->next->name))
  335.       break;
  336.   if (node->next)
  337.     {
  338.       temp = node->next;
  339.       unlink (temp->name);
  340.       free (temp->name);
  341.       node->next = temp->next;
  342.       free ((char *) temp);
  343.     }
  344. }
  345.  
  346. /* Initialize the character class tables. */
  347.  
  348. static void
  349. inittables ()
  350. {
  351.   int i;
  352.  
  353.   for (i = 0; i < UCHAR_LIM; ++i)
  354.     {
  355.       if (isblank (i))
  356.     blanks[i] = 1;
  357.       if (ISDIGIT (i))
  358.     digits[i] = 1;
  359.       if (!ISPRINT (i))
  360.     nonprinting[i] = 1;
  361.       if (!ISALNUM (i) && !isblank (i))
  362.     nondictionary[i] = 1;
  363.       if (ISLOWER (i))
  364.     fold_toupper[i] = toupper (i);
  365.       else
  366.     fold_toupper[i] = i;
  367.     }
  368. }
  369.  
  370. /* Initialize BUF, allocating ALLOC bytes initially. */
  371.  
  372. static void
  373. initbuf (buf, alloc)
  374.      struct buffer *buf;
  375.      int alloc;
  376. {
  377.   buf->alloc = alloc;
  378.   buf->buf = xmalloc (buf->alloc);
  379.   buf->used = buf->left = 0;
  380. }
  381.  
  382. /* Fill BUF reading from FP, moving buf->left bytes from the end
  383.    of buf->buf to the beginning first.    If EOF is reached and the
  384.    file wasn't terminated by a newline, supply one.  Return a count
  385.    of bytes buffered. */
  386.  
  387. static int
  388. fillbuf (buf, fp)
  389.      struct buffer *buf;
  390.      FILE *fp;
  391. {
  392.   int cc;
  393.  
  394.   bcopy (buf->buf + buf->used - buf->left, buf->buf, buf->left);
  395.   buf->used = buf->left;
  396.  
  397.   while (!feof (fp) && (buf->used == 0 || !memchr (buf->buf, '\n', buf->used)))
  398.     {
  399.       if (buf->used == buf->alloc)
  400.     {
  401.       buf->alloc *= 2;
  402.       buf->buf = xrealloc (buf->buf, buf->alloc);
  403.     }
  404.       cc = fread (buf->buf + buf->used, 1, buf->alloc - buf->used, fp);
  405.       if (ferror (fp))
  406.     {
  407.       error (0, errno, "read error");
  408.       cleanup ();
  409.       exit (2);
  410.     }
  411.       buf->used += cc;
  412.     }
  413.  
  414.   if (feof (fp) && buf->used && buf->buf[buf->used - 1] != '\n')
  415.     {
  416.       if (buf->used == buf->alloc)
  417.     {
  418.       buf->alloc *= 2;
  419.       buf->buf = xrealloc (buf->buf, buf->alloc);
  420.     }
  421.       buf->buf[buf->used++] = '\n';
  422.     }
  423.  
  424.   return buf->used;
  425. }
  426.  
  427. /* Initialize LINES, allocating space for ALLOC lines initially.
  428.    LIMIT is the maximum possible number of lines to allocate space
  429.    for, ever.  */
  430.  
  431. static void
  432. initlines (lines, alloc, limit)
  433.      struct lines *lines;
  434.      int alloc;
  435.      int limit;
  436. {
  437.   lines->alloc = alloc;
  438.   lines->lines = (struct line *) xmalloc (lines->alloc * sizeof (struct line));
  439.   lines->used = 0;
  440.   lines->limit = limit;
  441. }
  442.  
  443. /* Return a pointer to the first character of the field specified
  444.    by KEY in LINE. */
  445.  
  446. static char *
  447. begfield (line, key)
  448.      struct line *line;
  449.      struct keyfield *key;
  450. {
  451.   register char *ptr = line->text, *lim = ptr + line->length;
  452.   register int sword = key->sword, schar = key->schar;
  453.  
  454.   if (tab)
  455.     while (ptr < lim && sword--)
  456.       {
  457.     while (ptr < lim && *ptr != tab)
  458.       ++ptr;
  459.     if (ptr < lim)
  460.       ++ptr;
  461.       }
  462.   else
  463.     while (ptr < lim && sword--)
  464.       {
  465.     while (ptr < lim && blanks[UCHAR (*ptr)])
  466.       ++ptr;
  467.     while (ptr < lim && !blanks[UCHAR (*ptr)])
  468.       ++ptr;
  469.       }
  470.  
  471.   if (key->skipsblanks)
  472.     while (ptr < lim && blanks[UCHAR (*ptr)])
  473.       ++ptr;
  474.  
  475.   while (ptr < lim && schar--)
  476.     ++ptr;
  477.  
  478.   return ptr;
  479. }
  480.  
  481. /* Return the limit of (a pointer to the first character after) the field
  482.    in LINE specified by KEY. */
  483.  
  484. static char *
  485. limfield (line, key)
  486.      struct line *line;
  487.      struct keyfield *key;
  488. {
  489.   register char *ptr = line->text, *lim = ptr + line->length;
  490.   register int eword = key->eword, echar = key->echar;
  491.  
  492.   if (tab)
  493.     while (ptr < lim && eword--)
  494.       {
  495.     while (ptr < lim && *ptr != tab)
  496.       ++ptr;
  497.     if (ptr < lim && (eword || key->skipeblanks))
  498.       ++ptr;
  499.       }
  500.   else
  501.     while (ptr < lim && eword--)
  502.       {
  503.     while (ptr < lim && blanks[UCHAR (*ptr)])
  504.       ++ptr;
  505.     while (ptr < lim && !blanks[UCHAR (*ptr)])
  506.       ++ptr;
  507.       }
  508.  
  509.   if (key->skipeblanks)
  510.     while (ptr < lim && blanks[UCHAR (*ptr)])
  511.       ++ptr;
  512.  
  513.   while (ptr < lim && echar--)
  514.     ++ptr;
  515.  
  516.   return ptr;
  517. }
  518.  
  519. /* Find the lines in BUF, storing pointers and lengths in LINES.
  520.    Also replace newlines with NULs. */
  521.  
  522. static void
  523. findlines (buf, lines)
  524.      struct buffer *buf;
  525.      struct lines *lines;
  526. {
  527.   register char *beg = buf->buf, *lim = buf->buf + buf->used, *ptr;
  528.   struct keyfield *key = keyhead.next;
  529.  
  530.   lines->used = 0;
  531.  
  532.   while (beg < lim && (ptr = memchr (beg, '\n', lim - beg))
  533.      && lines->used < lines->limit)
  534.     {
  535.       /* There are various places in the code that rely on a NUL
  536.      being at the end of in-core lines; NULs inside the lines
  537.      will not cause trouble, though. */
  538.       *ptr = '\0';
  539.  
  540.       if (lines->used == lines->alloc)
  541.     {
  542.       lines->alloc *= 2;
  543.       lines->lines = (struct line *)
  544.         xrealloc ((char *) lines->lines,
  545.               lines->alloc * sizeof (struct line));
  546.     }
  547.  
  548.       lines->lines[lines->used].text = beg;
  549.       lines->lines[lines->used].length = ptr - beg;
  550.  
  551.       /* Precompute the position of the first key for efficiency. */
  552.       if (key)
  553.     {
  554.       if (key->eword >= 0)
  555.         lines->lines[lines->used].keylim =
  556.           limfield (&lines->lines[lines->used], key);
  557.       else
  558.         lines->lines[lines->used].keylim = ptr;
  559.  
  560.       if (key->sword >= 0)
  561.         lines->lines[lines->used].keybeg =
  562.           begfield (&lines->lines[lines->used], key);
  563.       else
  564.         {
  565.           if (key->skipsblanks)
  566.         while (blanks[UCHAR (*beg)])
  567.           ++beg;
  568.           lines->lines[lines->used].keybeg = beg;
  569.         }
  570.     }
  571.  
  572.       ++lines->used;
  573.       beg = ptr + 1;
  574.     }
  575.  
  576.   buf->left = lim - beg;
  577. }
  578.  
  579. /* Compare strings A and B containing decimal fractions < 1.  Each string
  580.    should begin with a decimal point followed immediately by the digits
  581.    of the fraction.  Strings not of this form are considered to be zero. */
  582.  
  583. static int
  584. fraccompare (a, b)
  585.      register char *a, *b;
  586. {
  587.   register tmpa = UCHAR (*a), tmpb = UCHAR (*b);
  588.  
  589.   if (tmpa == '.' && tmpb == '.')
  590.     {
  591.       do
  592.     tmpa = UCHAR (*++a), tmpb = UCHAR (*++b);
  593.       while (tmpa == tmpb && digits[tmpa]);
  594.       if (digits[tmpa] && digits[tmpb])
  595.     return tmpa - tmpb;
  596.       if (digits[tmpa])
  597.     {
  598.       while (tmpa == '0')
  599.         tmpa = UCHAR (*++a);
  600.       if (digits[tmpa])
  601.         return 1;
  602.       return 0;
  603.     }
  604.       if (digits[tmpb])
  605.     {
  606.       while (tmpb == '0')
  607.         tmpb = UCHAR (*++b);
  608.       if (digits[tmpb])
  609.         return -1;
  610.       return 0;
  611.     }
  612.       return 0;
  613.     }
  614.   else if (tmpa == '.')
  615.     {
  616.       do
  617.     tmpa = UCHAR (*++a);
  618.       while (tmpa == '0');
  619.       if (digits[tmpa])
  620.     return 1;
  621.       return 0;
  622.     }
  623.   else if (tmpb == '.')
  624.     {
  625.       do
  626.     tmpb = UCHAR (*++b);
  627.       while (tmpb == '0');
  628.       if (digits[tmpb])
  629.     return -1;
  630.       return 0;
  631.     }
  632.   return 0;
  633. }
  634.  
  635. /* Compare strings A and B as numbers without explicitly converting them to
  636.    machine numbers.  Comparatively slow for short strings, but asymptotically
  637.    hideously fast. */
  638.  
  639. static int
  640. numcompare (a, b)
  641.      register char *a, *b;
  642. {
  643.   register int tmpa, tmpb, loga, logb, tmp;
  644.  
  645.   tmpa = UCHAR (*a), tmpb = UCHAR (*b);
  646.  
  647.   if (tmpa == '-')
  648.     {
  649.       tmpa = UCHAR (*++a);
  650.       if (tmpb != '-')
  651.     {
  652.       if (digits[tmpa] && digits[tmpb])
  653.         return -1;
  654.       return 0;
  655.     }
  656.       tmpb = UCHAR (*++b);
  657.  
  658.       while (tmpa == '0')
  659.     tmpa = UCHAR (*++a);
  660.       while (tmpb == '0')
  661.     tmpb = UCHAR (*++b);
  662.  
  663.       while (tmpa == tmpb && digits[tmpa])
  664.     tmpa = UCHAR (*++a), tmpb = UCHAR (*++b);
  665.  
  666.       if ((tmpa == '.' && !digits[tmpb]) || (tmpb == '.' && !digits[tmpa]))
  667.     return -fraccompare (a, b);
  668.  
  669.       if (digits[tmpa])
  670.     for (loga = 1; digits[UCHAR (*++a)]; ++loga)
  671.       ;
  672.       else
  673.     loga = 0;
  674.  
  675.       if (digits[tmpb])
  676.     for (logb = 1; digits[UCHAR (*++b)]; ++logb)
  677.       ;
  678.       else
  679.     logb = 0;
  680.  
  681.       if (tmp = logb - loga)
  682.     return tmp;
  683.  
  684.       if (!loga)
  685.     return 0;
  686.  
  687.       return tmpb - tmpa;
  688.     }
  689.   else if (tmpb == '-')
  690.     {
  691.       if (digits[UCHAR (tmpa)] && digits[UCHAR (*++b)])
  692.     return 1;
  693.       return 0;
  694.     }
  695.   else
  696.     {
  697.       while (tmpa == '0')
  698.     tmpa = UCHAR (*++a);
  699.       while (tmpb == '0')
  700.     tmpb = UCHAR (*++b);
  701.  
  702.       while (tmpa == tmpb && digits[tmpa])
  703.     tmpa = UCHAR (*++a), tmpb = UCHAR (*++b);
  704.  
  705.       if ((tmpa == '.' && !digits[tmpb]) || (tmpb == '.' && !digits[tmpa]))
  706.     return fraccompare (a, b);
  707.  
  708.       if (digits[tmpa])
  709.     for (loga = 1; digits[UCHAR (*++a)]; ++loga)
  710.       ;
  711.       else
  712.     loga = 0;
  713.  
  714.       if (digits[tmpb])
  715.     for (logb = 1; digits[UCHAR (*++b)]; ++logb)
  716.       ;
  717.       else
  718.     logb = 0;
  719.  
  720.       if (tmp = loga - logb)
  721.     return tmp;
  722.  
  723.       if (!loga)
  724.     return 0;
  725.  
  726.       return tmpa - tmpb;
  727.     }
  728. }
  729.  
  730. /* Return an integer <= 12 associated with month name S with length LEN,
  731.    0 if the name in S is not recognized. */
  732.  
  733. static int
  734. getmonth (s, len)
  735.      char *s;
  736.      int len;
  737. {
  738.   char month[4];
  739.   register int i, lo = 0, hi = 12;
  740.  
  741.   if (len < 3)
  742.     return 0;
  743.  
  744.   for (i = 0; i < 3; ++i)
  745.     month[i] = fold_toupper[UCHAR (s[i])];
  746.   month[3] = '\0';
  747.  
  748.   while (hi - lo > 1)
  749.     if (strcmp (month, monthtab[(lo + hi) / 2].name) < 0)
  750.       hi = (lo + hi) / 2;
  751.     else
  752.       lo = (lo + hi) / 2;
  753.   if (!strcmp (month, monthtab[lo].name))
  754.     return monthtab[lo].val;
  755.   return 0;
  756. }
  757.  
  758. /* Compare two lines A and B trying every key in sequence until there
  759.    are no more keys or a difference is found. */
  760.  
  761. static int
  762. keycompare (a, b)
  763.      struct line *a, *b;
  764. {
  765.   register char *texta, *textb, *lima, *limb, *translate;
  766.   register int *ignore;
  767.   struct keyfield *key;
  768.   int diff = 0, iter = 0, lena, lenb;
  769.  
  770.   for (key = keyhead.next; key; key = key->next, ++iter)
  771.     {
  772.       ignore = key->ignore;
  773.       translate = key->translate;
  774.  
  775.       /* Find the beginning and limit of each field. */
  776.       if (iter || a->keybeg == NULL || b->keybeg == NULL)
  777.     {
  778.       if (key->eword >= 0)
  779.         lima = limfield (a, key), limb = limfield (b, key);
  780.       else
  781.         lima = a->text + a->length, limb = b->text + b->length;
  782.  
  783.       if (key->sword >= 0)
  784.         texta = begfield (a, key), textb = begfield (b, key);
  785.       else
  786.         {
  787.           texta = a->text, textb = b->text;
  788.           if (key->skipsblanks)
  789.         {
  790.           while (texta < lima && blanks[UCHAR (*texta)])
  791.             ++texta;
  792.           while (textb < limb && blanks[UCHAR (*textb)])
  793.             ++textb;
  794.         }
  795.         }
  796.     }
  797.       else
  798.     {
  799.       /* For the first iteration only, the key positions have
  800.          been precomputed for us. */
  801.       texta = a->keybeg, lima = a->keylim;
  802.       textb = b->keybeg, limb = b->keylim;
  803.     }
  804.  
  805.       /* Find the lengths. */
  806.       lena = lima - texta, lenb = limb - textb;
  807.       if (lena < 0)
  808.     lena = 0;
  809.       if (lenb < 0)
  810.     lenb = 0;
  811.  
  812.       /* Actually compare the fields. */
  813.       if (key->numeric)
  814.     {
  815.       if (*lima || *limb)
  816.         {
  817.           char savea = *lima, saveb = *limb;
  818.  
  819.           *lima = *limb = '\0';
  820.           diff = numcompare (texta, textb);
  821.           *lima = savea, *limb = saveb;
  822.         }
  823.       else
  824.         diff = numcompare (texta, textb);
  825.  
  826.       if (diff)
  827.         return key->reverse ? -diff : diff;
  828.       continue;
  829.     }
  830.       else if (key->month)
  831.     {
  832.       diff = getmonth (texta, lena) - getmonth (textb, lenb);
  833.       if (diff)
  834.         return key->reverse ? -diff : diff;
  835.       continue;
  836.     }
  837.       else if (ignore && translate)
  838.     while (texta < lima && textb < limb)
  839.       {
  840.         while (texta < lima && ignore[UCHAR (*texta)])
  841.           ++texta;
  842.         while (textb < limb && ignore[UCHAR (*textb)])
  843.           ++textb;
  844.         if (texta < lima && textb < limb &&
  845.         translate[UCHAR (*texta++)] != translate[UCHAR (*textb++)])
  846.           {
  847.         diff = translate[UCHAR (*--texta)] - translate[UCHAR (*--textb)];
  848.         break;
  849.           }
  850.       }
  851.       else if (ignore)
  852.     while (texta < lima && textb < limb)
  853.       {
  854.         while (texta < lima && ignore[UCHAR (*texta)])
  855.           ++texta;
  856.         while (textb < limb && ignore[UCHAR (*textb)])
  857.           ++textb;
  858.         if (texta < lima && textb < limb && *texta++ != *textb++)
  859.           {
  860.         diff = *--texta - *--textb;
  861.         break;
  862.           }
  863.       }
  864.       else if (translate)
  865.     while (texta < lima && textb < limb)
  866.       {
  867.         if (translate[UCHAR (*texta++)] != translate[UCHAR (*textb++)])
  868.           {
  869.         diff = translate[UCHAR (*--texta)] - translate[UCHAR (*--textb)];
  870.         break;
  871.           }
  872.       }
  873.       else
  874.     diff = memcmp (texta, textb, min (lena, lenb));
  875.  
  876.       if (diff)
  877.     return key->reverse ? -diff : diff;
  878.       if (diff = lena - lenb)
  879.     return key->reverse ? -diff : diff;
  880.     }
  881.  
  882.   return 0;
  883. }
  884.  
  885. /* Compare two lines A and B, returning negative, zero, or positive
  886.    depending on whether A compares less than, equal to, or greater than B. */
  887.  
  888. static int
  889. compare (a, b)
  890.      register struct line *a, *b;
  891. {
  892.   int diff, tmpa, tmpb, mini;
  893.  
  894.   if (keyhead.next)
  895.     {
  896.       diff = keycompare (a, b);
  897.       if (diff)
  898.     return diff;
  899.       if (!unique && !stable)
  900.     {
  901.       tmpa = a->length, tmpb = b->length;
  902.       diff = memcmp (a->text, b->text, min (tmpa, tmpb));
  903.       if (!diff)
  904.         diff = tmpa - tmpb;
  905.     }
  906.     }
  907.   else
  908.     {
  909.       tmpa = a->length, tmpb = b->length;
  910.       mini = min (tmpa, tmpb);
  911.       if (mini == 0)
  912.     diff = tmpa - tmpb;
  913.       else
  914.     {
  915.       char *ap = a->text, *bp = b->text;
  916.  
  917.       diff = *ap - *bp;
  918.       if (diff == 0)
  919.         {
  920.           diff = memcmp (ap, bp, mini);
  921.           if (diff == 0)
  922.         diff = tmpa - tmpb;
  923.         }
  924.     }
  925.     }
  926.  
  927.   return reverse ? -diff : diff;
  928. }
  929.  
  930. /* Check that the lines read from the given FP come in order.  Return
  931.    1 if they do and 0 if there is a disorder. */
  932.  
  933. static int
  934. checkfp (fp)
  935.      FILE *fp;
  936. {
  937.   struct buffer buf;        /* Input buffer. */
  938.   struct lines lines;        /* Lines scanned from the buffer. */
  939.   struct line temp;        /* Copy of previous line. */
  940.   int cc;            /* Character count. */
  941.   int cmp;            /* Result of calling compare. */
  942.   int alloc, i, success = 1;
  943.  
  944.   initbuf (&buf, mergealloc);
  945.   initlines (&lines, mergealloc / linelength + 1,
  946.          LINEALLOC / ((NMERGE + NMERGE) * sizeof (struct line)));
  947.   alloc = linelength;
  948.   temp.text = xmalloc (alloc);
  949.  
  950.   cc = fillbuf (&buf, fp);
  951.   findlines (&buf, &lines);
  952.  
  953.   if (cc)
  954.     do
  955.       {
  956.     /* Compare each line in the buffer with its successor. */
  957.     for (i = 0; i < lines.used - 1; ++i)
  958.       {
  959.         cmp = compare (&lines.lines[i], &lines.lines[i + 1]);
  960.         if ((unique && cmp >= 0) || (cmp > 0))
  961.           {
  962.         success = 0;
  963.         goto finish;
  964.           }
  965.       }
  966.  
  967.     /* Save the last line of the buffer and refill the buffer. */
  968.     if (lines.lines[lines.used - 1].length > alloc)
  969.       {
  970.         while (lines.lines[lines.used - 1].length + 1 > alloc)
  971.           alloc *= 2;
  972.         temp.text = xrealloc (temp.text, alloc);
  973.       }
  974.     bcopy (lines.lines[lines.used - 1].text, temp.text,
  975.            lines.lines[lines.used - 1].length + 1);
  976.     temp.length = lines.lines[lines.used - 1].length;
  977.  
  978.     cc = fillbuf (&buf, fp);
  979.     if (cc)
  980.       {
  981.         findlines (&buf, &lines);
  982.         /* Make sure the line saved from the old buffer contents is
  983.            less than or equal to the first line of the new buffer. */
  984.         cmp = compare (&temp, &lines.lines[0]);
  985.         if ((unique && cmp >= 0) || (cmp > 0))
  986.           {
  987.         success = 0;
  988.         break;
  989.           }
  990.       }
  991.       }
  992.     while (cc);
  993.  
  994. finish:
  995.   xfclose (fp);
  996.   free (buf.buf);
  997.   free ((char *) lines.lines);
  998.   free (temp.text);
  999.   return success;
  1000. }
  1001.  
  1002. /* Merge lines from FPS onto OFP.  NFPS cannot be greater than NMERGE.
  1003.    Close FPS before returning. */
  1004.  
  1005. static void
  1006. mergefps (fps, nfps, ofp)
  1007.      FILE *fps[], *ofp;
  1008.      register int nfps;
  1009. {
  1010.   struct buffer buffer[NMERGE];    /* Input buffers for each file. */
  1011.   struct lines lines[NMERGE];    /* Line tables for each buffer. */
  1012.   struct line saved;        /* Saved line for unique check. */
  1013.   int savedflag = 0;        /* True if there is a saved line. */
  1014.   int savealloc;        /* Size allocated for the saved line. */
  1015.   int cur[NMERGE];        /* Current line in each line table. */
  1016.   int ord[NMERGE];        /* Table representing a permutation of fps,
  1017.                    such that lines[ord[0]].lines[cur[ord[0]]]
  1018.                    is the smallest line and will be next
  1019.                    output. */
  1020.   register int i, j, t;
  1021.  
  1022.   /* Allocate space for a saved line if necessary. */
  1023.   if (unique)
  1024.     {
  1025.       savealloc = linelength;
  1026.       saved.text = xmalloc (savealloc);
  1027.     }
  1028.  
  1029.   /* Read initial lines from each input file. */
  1030.   for (i = 0; i < nfps; ++i)
  1031.     {
  1032.       initbuf (&buffer[i], mergealloc);
  1033.       /* If a file is empty, eliminate it from future consideration. */
  1034.       while (i < nfps && !fillbuf (&buffer[i], fps[i]))
  1035.     {
  1036.       xfclose (fps[i]);
  1037.       --nfps;
  1038.       for (j = i; j < nfps; ++j)
  1039.         fps[j] = fps[j + 1];
  1040.     }
  1041.       if (i == nfps)
  1042.     free (buffer[i].buf);
  1043.       else
  1044.     {
  1045.       initlines (&lines[i], mergealloc / linelength + 1,
  1046.              LINEALLOC / ((NMERGE + NMERGE) * sizeof (struct line)));
  1047.       findlines (&buffer[i], &lines[i]);
  1048.       cur[i] = 0;
  1049.     }
  1050.     }
  1051.  
  1052.   /* Set up the ord table according to comparisons among input lines.
  1053.      Since this only reorders two items if one is strictly greater than
  1054.      the other, it is stable. */
  1055.   for (i = 0; i < nfps; ++i)
  1056.     ord[i] = i;
  1057.   for (i = 1; i < nfps; ++i)
  1058.     if (compare (&lines[ord[i - 1]].lines[cur[ord[i - 1]]],
  1059.          &lines[ord[i]].lines[cur[ord[i]]]) > 0)
  1060.       t = ord[i - 1], ord[i - 1] = ord[i], ord[i] = t, i = 0;
  1061.  
  1062.   /* Repeatedly output the smallest line until no input remains. */
  1063.   while (nfps)
  1064.     {
  1065.       /* If uniqified output is turned out, output only the first of
  1066.      an identical series of lines. */
  1067.       if (unique)
  1068.     {
  1069.       if (savedflag && compare (&saved, &lines[ord[0]].lines[cur[ord[0]]]))
  1070.         {
  1071.           xfwrite (saved.text, 1, saved.length, ofp);
  1072.           putc ('\n', ofp);
  1073.           savedflag = 0;
  1074.         }
  1075.       if (!savedflag)
  1076.         {
  1077.           if (savealloc < lines[ord[0]].lines[cur[ord[0]]].length + 1)
  1078.         {
  1079.           while (savealloc < lines[ord[0]].lines[cur[ord[0]]].length + 1)
  1080.             savealloc *= 2;
  1081.           saved.text = xrealloc (saved.text, savealloc);
  1082.         }
  1083.           saved.length = lines[ord[0]].lines[cur[ord[0]]].length;
  1084.           bcopy (lines[ord[0]].lines[cur[ord[0]]].text, saved.text,
  1085.              saved.length + 1);
  1086.           savedflag = 1;
  1087.         }
  1088.     }
  1089.       else
  1090.     {
  1091.       xfwrite (lines[ord[0]].lines[cur[ord[0]]].text, 1,
  1092.            lines[ord[0]].lines[cur[ord[0]]].length, ofp);
  1093.       putc ('\n', ofp);
  1094.     }
  1095.  
  1096.       /* Check if we need to read more lines into core. */
  1097.       if (++cur[ord[0]] == lines[ord[0]].used)
  1098.     if (fillbuf (&buffer[ord[0]], fps[ord[0]]))
  1099.       {
  1100.         findlines (&buffer[ord[0]], &lines[ord[0]]);
  1101.         cur[ord[0]] = 0;
  1102.       }
  1103.     else
  1104.       {
  1105.         /* We reached EOF on fps[ord[0]]. */
  1106.         for (i = 1; i < nfps; ++i)
  1107.           if (ord[i] > ord[0])
  1108.         --ord[i];
  1109.         --nfps;
  1110.         xfclose (fps[ord[0]]);
  1111.         free (buffer[ord[0]].buf);
  1112.         free ((char *) lines[ord[0]].lines);
  1113.         for (i = ord[0]; i < nfps; ++i)
  1114.           {
  1115.         fps[i] = fps[i + 1];
  1116.         buffer[i] = buffer[i + 1];
  1117.         lines[i] = lines[i + 1];
  1118.         cur[i] = cur[i + 1];
  1119.           }
  1120.         for (i = 0; i < nfps; ++i)
  1121.           ord[i] = ord[i + 1];
  1122.         continue;
  1123.       }
  1124.  
  1125.       /* The new line just read in may be larger than other lines
  1126.      already in core; push it back in the queue until we encounter
  1127.      a line larger than it. */
  1128.       for (i = 1; i < nfps; ++i)
  1129.     {
  1130.       t = compare (&lines[ord[0]].lines[cur[ord[0]]],
  1131.                &lines[ord[i]].lines[cur[ord[i]]]);
  1132.       if (!t)
  1133.         t = ord[0] - ord[i];
  1134.       if (t < 0)
  1135.         break;
  1136.     }
  1137.       t = ord[0];
  1138.       for (j = 1; j < i; ++j)
  1139.     ord[j - 1] = ord[j];
  1140.       ord[i - 1] = t;
  1141.     }
  1142.  
  1143.   if (unique && savedflag)
  1144.     {
  1145.       xfwrite (saved.text, 1, saved.length, ofp);
  1146.       putc ('\n', ofp);
  1147.       free (saved.text);
  1148.     }
  1149. }
  1150.  
  1151. /* Sort the array LINES with NLINES members, using TEMP for temporary space. */
  1152.  
  1153. static void
  1154. sortlines (lines, nlines, temp)
  1155.      struct line *lines, *temp;
  1156.      int nlines;
  1157. {
  1158.   register struct line *lo, *hi, *t;
  1159.   register int nlo, nhi;
  1160.  
  1161.   if (nlines == 2)
  1162.     {
  1163.       if (compare (&lines[0], &lines[1]) > 0)
  1164.     *temp = lines[0], lines[0] = lines[1], lines[1] = *temp;
  1165.       return;
  1166.     }
  1167.  
  1168.   nlo = nlines / 2;
  1169.   lo = lines;
  1170.   nhi = nlines - nlo;
  1171.   hi = lines + nlo;
  1172.  
  1173.   if (nlo > 1)
  1174.     sortlines (lo, nlo, temp);
  1175.  
  1176.   if (nhi > 1)
  1177.     sortlines (hi, nhi, temp);
  1178.  
  1179.   t = temp;
  1180.  
  1181.   while (nlo && nhi)
  1182.     if (compare (lo, hi) <= 0)
  1183.       *t++ = *lo++, --nlo;
  1184.     else
  1185.       *t++ = *hi++, --nhi;
  1186.   while (nlo--)
  1187.     *t++ = *lo++;
  1188.  
  1189.   for (lo = lines, nlo = nlines - nhi, t = temp; nlo; --nlo)
  1190.     *lo++ = *t++;
  1191. }
  1192.  
  1193. /* Check that each of the NFILES FILES is ordered.
  1194.    Return a count of disordered files. */
  1195.  
  1196. static int
  1197. check (files, nfiles)
  1198.      char *files[];
  1199.      int nfiles;
  1200. {
  1201.   int i, disorders = 0;
  1202.   FILE *fp;
  1203.  
  1204.   for (i = 0; i < nfiles; ++i)
  1205.     {
  1206.       fp = xfopen (files[i], "r");
  1207.       if (!checkfp (fp))
  1208.     {
  1209.       printf ("%s: disorder on %s\n", program_name, files[i]);
  1210.       ++disorders;
  1211.     }
  1212.     }
  1213.   return disorders;
  1214. }
  1215.  
  1216. /* Merge NFILES FILES onto OFP. */
  1217.  
  1218. static void
  1219. merge (files, nfiles, ofp)
  1220.      char *files[];
  1221.      int nfiles;
  1222.      FILE *ofp;
  1223. {
  1224.   int i, j, t;
  1225.   char *temp;
  1226.   FILE *fps[NMERGE], *tfp;
  1227.  
  1228.   while (nfiles > NMERGE)
  1229.     {
  1230.       t = 0;
  1231.       for (i = 0; i < nfiles / NMERGE; ++i)
  1232.     {
  1233.       for (j = 0; j < NMERGE; ++j)
  1234.         fps[j] = xfopen (files[i * NMERGE + j], "r");
  1235.       tfp = xfopen (temp = tempname (), "w");
  1236.       mergefps (fps, NMERGE, tfp);
  1237.       xfclose (tfp);
  1238.       for (j = 0; j < NMERGE; ++j)
  1239.         zaptemp (files[i * NMERGE + j]);
  1240.       files[t++] = temp;
  1241.     }
  1242.       for (j = 0; j < nfiles % NMERGE; ++j)
  1243.     fps[j] = xfopen (files[i * NMERGE + j], "r");
  1244.       tfp = xfopen (temp = tempname (), "w");
  1245.       mergefps (fps, nfiles % NMERGE, tfp);
  1246.       xfclose (tfp);
  1247.       for (j = 0; j < nfiles % NMERGE; ++j)
  1248.     zaptemp (files[i * NMERGE + j]);
  1249.       files[t++] = temp;
  1250.       nfiles = t;
  1251.     }
  1252.  
  1253.   for (i = 0; i < nfiles; ++i)
  1254.     fps[i] = xfopen (files[i], "r");
  1255.   mergefps (fps, i, ofp);
  1256.   for (i = 0; i < nfiles; ++i)
  1257.     zaptemp (files[i]);
  1258. }
  1259.  
  1260. /* Sort NFILES FILES onto OFP. */
  1261.  
  1262. static void
  1263. sort (files, nfiles, ofp)
  1264.      char **files;
  1265.      int nfiles;
  1266.      FILE *ofp;
  1267. {
  1268.   struct buffer buf;
  1269.   struct lines lines;
  1270.   struct line *tmp;
  1271.   int i, ntmp;
  1272.   FILE *fp, *tfp;
  1273.   struct tempnode *node;
  1274.   int ntemp = 0;
  1275.   char **tempfiles;
  1276.  
  1277.   initbuf (&buf, sortalloc);
  1278.   initlines (&lines, sortalloc / linelength + 1,
  1279.          LINEALLOC / sizeof (struct line));
  1280.   ntmp = lines.alloc;
  1281.   tmp = (struct line *) xmalloc (ntmp * sizeof (struct line));
  1282.  
  1283.   while (nfiles--)
  1284.     {
  1285.       fp = xfopen (*files++, "r");
  1286.       while (fillbuf (&buf, fp))
  1287.     {
  1288.       findlines (&buf, &lines);
  1289.       if (lines.used > ntmp)
  1290.         {
  1291.           while (lines.used > ntmp)
  1292.         ntmp *= 2;
  1293.           tmp = (struct line *)
  1294.         xrealloc ((char *) tmp, ntmp * sizeof (struct line));
  1295.         }
  1296.       sortlines (lines.lines, lines.used, tmp);
  1297.       if (feof (fp) && !nfiles && !ntemp && !buf.left)
  1298.         tfp = ofp;
  1299.       else
  1300.         {
  1301.           ++ntemp;
  1302.           tfp = xfopen (tempname (), "w");
  1303.         }
  1304.       for (i = 0; i < lines.used; ++i)
  1305.         if (!unique || i == 0
  1306.         || compare (&lines.lines[i], &lines.lines[i - 1]))
  1307.           {
  1308.         xfwrite (lines.lines[i].text, 1, lines.lines[i].length, tfp);
  1309.         putc ('\n', tfp);
  1310.           }
  1311.       if (tfp != ofp)
  1312.         xfclose (tfp);
  1313.     }
  1314.       xfclose (fp);
  1315.     }
  1316.  
  1317.   free (buf.buf);
  1318.   free ((char *) lines.lines);
  1319.   free ((char *) tmp);
  1320.  
  1321.   if (ntemp)
  1322.     {
  1323.       tempfiles = (char **) xmalloc (ntemp * sizeof (char *));
  1324.       i = ntemp;
  1325.       for (node = temphead.next; node; node = node->next)
  1326.     tempfiles[--i] = node->name;
  1327.       merge (tempfiles, ntemp, ofp);
  1328.       free ((char *) tempfiles);
  1329.     }
  1330. }
  1331.  
  1332. /* Insert key KEY at the end of the list (`keyhead'). */
  1333.  
  1334. static void
  1335. insertkey (key)
  1336.      struct keyfield *key;
  1337. {
  1338.   struct keyfield *k = &keyhead;
  1339.  
  1340.   while (k->next)
  1341.     k = k->next;
  1342.   k->next = key;
  1343.   key->next = NULL;
  1344. }
  1345.  
  1346. static void
  1347. badfieldspec (s)
  1348.      char *s;
  1349. {
  1350.   error (2, 0, "invalid field specification `%s'", s);
  1351. }
  1352.  
  1353. /* Handle interrupts and hangups. */
  1354.  
  1355. static void
  1356. sighandler (sig)
  1357.      int sig;
  1358. {
  1359. #ifdef _POSIX_VERSION
  1360.   struct sigaction sigact;
  1361.  
  1362.   sigact.sa_handler = SIG_DFL;
  1363.   sigemptyset (&sigact.sa_mask);
  1364.   sigact.sa_flags = 0;
  1365.   sigaction (sig, &sigact, NULL);
  1366. #else                /* !_POSIX_VERSION */
  1367.   signal (sig, SIG_DFL);
  1368. #endif                /* _POSIX_VERSION */
  1369.   cleanup ();
  1370.   kill (getpid (), sig);
  1371. }
  1372.  
  1373. /* Set the ordering options for KEY specified in S.
  1374.    Return the address of the first character in S that
  1375.    is not a valid ordering option.
  1376.    BLANKTYPE is the kind of blanks that 'b' should skip. */
  1377.  
  1378. static char *
  1379. set_ordering (s, key, blanktype)
  1380.      register char *s;
  1381.      struct keyfield *key;
  1382.      enum blanktype blanktype;
  1383. {
  1384.   while (*s)
  1385.     {
  1386.       switch (*s)
  1387.     {
  1388.     case 'b':
  1389.       if (blanktype == bl_start || blanktype == bl_both)
  1390.         key->skipsblanks = 1;
  1391.       if (blanktype == bl_end || blanktype == bl_both)
  1392.         key->skipeblanks = 1;
  1393.       break;
  1394.     case 'd':
  1395.       key->ignore = nondictionary;
  1396.       break;
  1397.     case 'f':
  1398.       key->translate = fold_toupper;
  1399.       break;
  1400. #if 0
  1401.     case 'g':
  1402.       /* Reserved for comparing floating-point numbers. */
  1403.       break;
  1404. #endif
  1405.     case 'i':
  1406.       key->ignore = nonprinting;
  1407.       break;
  1408.     case 'M':
  1409.       key->skipsblanks = key->skipeblanks = key->month = 1;
  1410.       break;
  1411.     case 'n':
  1412.       key->skipsblanks = key->skipeblanks = key->numeric = 1;
  1413.       break;
  1414.     case 'r':
  1415.       key->reverse = 1;
  1416.       break;
  1417.     default:
  1418.       return s;
  1419.     }
  1420.       ++s;
  1421.     }
  1422.   return s;
  1423. }
  1424.  
  1425. void
  1426. main (argc, argv)
  1427.      int argc;
  1428.      char *argv[];
  1429. {
  1430.   struct keyfield *key = NULL, gkey;
  1431.   char *s;
  1432.   int i, t, t2;
  1433.   int checkonly = 0, mergeonly = 0, nfiles = 0;
  1434.   char *minus = "-", *outfile = minus, **files, *tmp;
  1435.   FILE *ofp;
  1436. #ifdef _POSIX_VERSION
  1437.   struct sigaction oldact, newact;
  1438. #endif                /* _POSIX_VERSION */
  1439.  
  1440.   program_name = argv[0];
  1441.   have_read_stdin = 0;
  1442.   inittables ();
  1443.  
  1444.   prefix = getenv ("TMPDIR");
  1445.   if (prefix == NULL)
  1446.     prefix = "/tmp";
  1447.  
  1448. #ifdef _POSIX_VERSION
  1449.   newact.sa_handler = sighandler;
  1450.   sigemptyset (&newact.sa_mask);
  1451.   newact.sa_flags = 0;
  1452.  
  1453.   sigaction (SIGINT, NULL, &oldact);
  1454.   if (oldact.sa_handler != SIG_IGN)
  1455.     sigaction (SIGINT, &newact, NULL);
  1456.   sigaction (SIGHUP, NULL, &oldact);
  1457.   if (oldact.sa_handler != SIG_IGN)
  1458.     sigaction (SIGHUP, &newact, NULL);
  1459. #else                /* !_POSIX_VERSION */
  1460.   if (signal (SIGINT, SIG_IGN) != SIG_IGN)
  1461.     signal (SIGINT, sighandler);
  1462. #ifdef SIGHUP
  1463.   if (signal (SIGHUP, SIG_IGN) != SIG_IGN)
  1464.     signal (SIGHUP, sighandler);
  1465. #endif
  1466. #endif                /* _POSIX_VERSION */
  1467.  
  1468.   gkey.sword = gkey.eword = -1;
  1469.   gkey.ignore = NULL;
  1470.   gkey.translate = NULL;
  1471.   gkey.numeric = gkey.month = gkey.reverse = 0;
  1472.   gkey.skipsblanks = gkey.skipeblanks = 0;
  1473.  
  1474.   files = (char **) xmalloc (sizeof (char *) * argc);
  1475.  
  1476.   for (i = 1; i < argc; ++i)
  1477.     {
  1478.       if (argv[i][0] == '+')
  1479.     {
  1480.       if (key)
  1481.         insertkey (key);
  1482.       key = (struct keyfield *) xmalloc (sizeof (struct keyfield));
  1483.       key->eword = -1;
  1484.       key->ignore = NULL;
  1485.       key->translate = NULL;
  1486.       key->skipsblanks = key->skipeblanks = 0;
  1487.       key->numeric = key->month = key->reverse = 0;
  1488.       s = argv[i] + 1;
  1489.       if (!digits[UCHAR (*s)])
  1490.         badfieldspec (argv[i]);
  1491.       for (t = 0; digits[UCHAR (*s)]; ++s)
  1492.         t = 10 * t + *s - '0';
  1493.       t2 = 0;
  1494.       if (*s == '.')
  1495.         for (++s; digits[UCHAR (*s)]; ++s)
  1496.           t2 = 10 * t2 + *s - '0';
  1497.       if (t2 || t)
  1498.         {
  1499.           key->sword = t;
  1500.           key->schar = t2;
  1501.         }
  1502.       else
  1503.         key->sword = -1;
  1504.       s = set_ordering (s, key, bl_start);
  1505.       if (*s)
  1506.         badfieldspec (argv[i]);
  1507.     }
  1508.       else if (argv[i][0] == '-')
  1509.     {
  1510.       if (!strcmp ("-", argv[i]))
  1511.         break;
  1512.       s = argv[i] + 1;
  1513.       if (digits[UCHAR (*s)])
  1514.         {
  1515.           if (!key)
  1516.         usage ();
  1517.           for (t = 0; digits[UCHAR (*s)]; ++s)
  1518.         t = t * 10 + *s - '0';
  1519.           t2 = 0;
  1520.           if (*s == '.')
  1521.         for (++s; digits[UCHAR (*s)]; ++s)
  1522.           t2 = t2 * 10 + *s - '0';
  1523.           key->eword = t;
  1524.           key->echar = t2;
  1525.           s = set_ordering (s, key, bl_end);
  1526.           if (*s)
  1527.         badfieldspec (argv[i]);
  1528.           insertkey (key);
  1529.           key = NULL;
  1530.         }
  1531.       else
  1532.         while (*s)
  1533.           {
  1534.         s = set_ordering (s, &gkey, bl_both);
  1535.         switch (*s)
  1536.           {
  1537.           case '\0':
  1538.             break;
  1539.           case 'c':
  1540.             checkonly = 1;
  1541.             break;
  1542.           case 'k':
  1543.             if (s[1])
  1544.               ++s;
  1545.             else
  1546.               {
  1547.             if (i == argc - 1)
  1548.               error (2, 0, "option `-k' requires an argument");
  1549.             else
  1550.               s = argv[++i];
  1551.               }
  1552.             if (key)
  1553.               insertkey (key);
  1554.             key = (struct keyfield *)
  1555.               xmalloc (sizeof (struct keyfield));
  1556.             key->eword = -1;
  1557.             key->ignore = NULL;
  1558.             key->translate = NULL;
  1559.             key->skipsblanks = key->skipeblanks = 0;
  1560.             key->numeric = key->month = key->reverse = 0;
  1561.             /* Get POS1. */
  1562.             if (!digits[UCHAR (*s)])
  1563.               badfieldspec (argv[i]);
  1564.             for (t = 0; digits[UCHAR (*s)]; ++s)
  1565.               t = 10 * t + *s - '0';
  1566.             if (t)
  1567.               t--;
  1568.             t2 = 0;
  1569.             if (*s == '.')
  1570.               {
  1571.             for (++s; digits[UCHAR (*s)]; ++s)
  1572.               t2 = 10 * t2 + *s - '0';
  1573.             if (t2)
  1574.               t2--;
  1575.               }
  1576.             if (t2 || t)
  1577.               {
  1578.             key->sword = t;
  1579.             key->schar = t2;
  1580.               }
  1581.             else
  1582.               key->sword = -1;
  1583.             s = set_ordering (s, key, bl_start);
  1584.             if (*s && *s != ',')
  1585.               badfieldspec (argv[i]);
  1586.             else if (*s++)
  1587.               {
  1588.             /* Get POS2. */
  1589.             for (t = 0; digits[UCHAR (*s)]; ++s)
  1590.               t = t * 10 + *s - '0';
  1591.             t2 = 0;
  1592.             if (*s == '.')
  1593.               {
  1594.                 for (++s; digits[UCHAR (*s)]; ++s)
  1595.                   t2 = t2 * 10 + *s - '0';
  1596.                 if (t2)
  1597.                   t--;
  1598.               }
  1599.             key->eword = t;
  1600.             key->echar = t2;
  1601.             s = set_ordering (s, key, bl_end);
  1602.             if (*s)
  1603.               badfieldspec (argv[i]);
  1604.               }
  1605.             insertkey (key);
  1606.             key = NULL;
  1607.             goto outer;
  1608.           case 'm':
  1609.             mergeonly = 1;
  1610.             break;
  1611.           case 'o':
  1612.             if (s[1])
  1613.               outfile = s + 1;
  1614.             else
  1615.               {
  1616.             if (i == argc - 1)
  1617.               error (2, 0, "option `-o' requires an argument");
  1618.             else
  1619.               outfile = argv[++i];
  1620.               }
  1621.             goto outer;
  1622.           case 's':
  1623.             stable = 1;
  1624.             break;
  1625.           case 't':
  1626.             if (s[1])
  1627.               tab = *++s;
  1628.             else if (i < argc - 1)
  1629.               {
  1630.             tab = *argv[++i];
  1631.             goto outer;
  1632.               }
  1633.             else
  1634.               error (2, 0, "option `-t' requires an argument");
  1635.             break;
  1636.           case 'u':
  1637.             unique = 1;
  1638.             break;
  1639.           default:
  1640.             fprintf (stderr, "%s: unrecognized option `-%c'\n",
  1641.                  argv[0], *s);
  1642.             usage ();
  1643.           }
  1644.         if (*s)
  1645.           ++s;
  1646.           }
  1647.     }
  1648.       else            /* Not an option. */
  1649.     {
  1650.       files[nfiles++] = argv[i];
  1651.     }
  1652.     outer:;
  1653.     }
  1654.  
  1655.   if (key)
  1656.     insertkey (key);
  1657.  
  1658.   /* Inheritance of global options to individual keys. */
  1659.   for (key = keyhead.next; key; key = key->next)
  1660.     if (!key->ignore && !key->translate && !key->skipsblanks && !key->reverse
  1661.     && !key->skipeblanks && !key->month && !key->numeric)
  1662.       {
  1663.     key->ignore = gkey.ignore;
  1664.     key->translate = gkey.translate;
  1665.     key->skipsblanks = gkey.skipsblanks;
  1666.     key->skipeblanks = gkey.skipeblanks;
  1667.     key->month = gkey.month;
  1668.     key->numeric = gkey.numeric;
  1669.     key->reverse = gkey.reverse;
  1670.       }
  1671.  
  1672.   if (!keyhead.next && (gkey.ignore || gkey.translate || gkey.skipsblanks
  1673.             || gkey.reverse || gkey.skipeblanks
  1674.             || gkey.month || gkey.numeric))
  1675.     insertkey (&gkey);
  1676.  
  1677.   if (nfiles == 0)
  1678.     {
  1679.       nfiles = 1;
  1680.       files = −
  1681.     }
  1682.  
  1683.   if (checkonly)
  1684.     exit (check (files, nfiles) != 0);
  1685.  
  1686.   if (strcmp (outfile, "-"))
  1687.     {
  1688.       for (i = 0; i < nfiles; ++i)
  1689.     if (!strcmp (outfile, files[i]))
  1690.       break;
  1691.       if (i == nfiles)
  1692.     ofp = xfopen (outfile, "w");
  1693.       else
  1694.     {
  1695.       char buf[8192];
  1696.       FILE *fp = xfopen (outfile, "r");
  1697.       int cc;
  1698.  
  1699.       tmp = tempname ();
  1700.       ofp = xfopen (tmp, "w");
  1701.       while ((cc = fread (buf, 1, sizeof buf, fp)) > 0)
  1702.         xfwrite (buf, 1, cc, ofp);
  1703.       if (ferror (fp))
  1704.         {
  1705.           error (0, errno, "%s", outfile);
  1706.           cleanup ();
  1707.           exit (2);
  1708.         }
  1709.       xfclose (ofp);
  1710.       xfclose (fp);
  1711.       files[i] = tmp;
  1712.       ofp = xfopen (outfile, "w");
  1713.     }
  1714.     }
  1715.   else
  1716.     ofp = stdout;
  1717.  
  1718.   if (mergeonly)
  1719.     merge (files, nfiles, ofp);
  1720.   else
  1721.     sort (files, nfiles, ofp);
  1722.   cleanup ();
  1723.  
  1724.   if (have_read_stdin && fclose (stdin) == EOF)
  1725.     error (1, errno, "-");
  1726.   if (ferror (stdout) || fclose (stdout) == EOF)
  1727.     error (1, 0, "write error");
  1728.  
  1729.   exit (0);
  1730. }
  1731.  
  1732. static void
  1733. usage ()
  1734. {
  1735.   fprintf (stderr, "\
  1736. Usage: %s [-cmus] [-t separator] [-o output-file] [-bdfiMnr] [+POS1 [-POS2]]\n\
  1737.        [-k POS1[,POS2]] [file...]\n",
  1738.        program_name);
  1739.   exit (2);
  1740. }
  1741.